package rdgl.shell;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import rdgl.antlr.RDGLLexer;
import rdgl.antlr.RDGLParser;
import rdgl.antlr.RDGLWalker;
import antlr.CommonAST;
import antlr.RecognitionException;
import antlr.TokenStreamException;

public class RDGL {

	/**
	 * The main entry point into the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {	
			while (true) {
				System.out.print("RDGL> ");

				InputStreamReader streamReader = new InputStreamReader(System.in);
				BufferedReader bufferedReader = new BufferedReader(streamReader);
				String line = bufferedReader.readLine();
			
				// allows for exiting the shell
				if (line.equals("exit") || line.equals("quit")) {
					System.out.println("Alas, all good things must come to an end.");
					break;
				}
				
				parse(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Returns a translated string given a (valud) input expression.
	 * @param line
	 */
	public static String parse(String line) {
        try {
        	if(line == null || line.trim().equals("")) {
        		return new String();
        	}
        	
    		InputStream input = new ByteArrayInputStream(line.getBytes());
    		RDGLLexer lexer = new RDGLLexer(input);
    		RDGLParser parser = new RDGLParser(lexer);
    		
            parser.program();
            CommonAST tree = (CommonAST)parser.getAST();
            RDGLWalker walker = new RDGLWalker();
            
            //for debugging purposes, out put the AST
            //System.out.println("Tree: " + tree.toStringList());
            
            String result = walker.program(tree);
            System.out.println(">> " + result);
            return result;
        } catch (RecognitionException ex)  {
            System.err.println(ex.getMessage());
        } catch (TokenStreamException ex) {
        	System.err.println(ex.getMessage());
		} catch (Exception ex) {
			System.err.println(ex.getMessage());
		} finally {
			System.out.println();
			System.err.flush();
		}
		return null;
	}
	

}
